﻿// Write a method that return the maximal element in a portion of array of integers starting at given index. Using it write another method that sorts an array in ascending / descending order.

using System;

class SortArrayWithGetMaxFromRange
{
    public enum Order
    {
        Ascending,
        Descending
    }

    public class MaxNumber
    {
        public int Value { get; set; }
        public int Index { get; set; }
    }

    static void Main()
    {
        int[] intArray = { 0, 11, 1, 2, 1, 0, 5, 4, -9, 1, 0 };
        int indexStart = 3;

        int maxNum = GetMaxFromPos(intArray, indexStart).Value;
        int maxNumIndex = GetMaxFromPos(intArray, indexStart).Index;
        Console.WriteLine("Biggest element in Range({0}, {1}) from the Array is {2} with index {3}", indexStart, intArray.Length - 1, maxNum, maxNumIndex);

        // Selection Sort by ascending order
        SelectionSort(intArray, Order.Ascending);
        Console.WriteLine("Sorted Array by ascending order:");
        PrintElements(intArray);

        // Selection Sort by descending order
        SelectionSort(intArray, Order.Descending);
        Console.WriteLine("Sorted Array by descending order:");
        PrintElements(intArray);
    }

    public static void SelectionSort(int[] intArray, Order order)
    {
        // sort by descending order
        for (int i = 0; i < intArray.Length; i++)
        {
            SwapElement(intArray, GetMaxFromPos(intArray, i).Index, i);
        }

        if (order.Equals(Order.Ascending))
        {
            Array.Reverse(intArray);
        }
    }

    public static MaxNumber GetMaxFromPos(int[] intArray, int indexStart)
    {
        int maxNum = intArray[indexStart];
        int maxNumIndex = indexStart;
        for (int i = indexStart; i < intArray.Length; i++)
        {
            int num = intArray[i];
            if (num > maxNum)
            {
                maxNum = num;
                maxNumIndex = i;
            }
        }

        return new MaxNumber
        {
            Value = maxNum,
            Index = maxNumIndex
        };
    }

    private static void SwapElement(int[] intArray, int index1, int index2)
    {
        int temp = intArray[index1];
        intArray[index1] = intArray[index2];
        intArray[index2] = temp;
    }

    private static void PrintElements(int[] intArray)
    {
        Console.Write("{");
        for (int i = 0; i < intArray.Length; i++)
        {
            Console.Write(intArray[i]);
            if (i != intArray.Length - 1)
            {
                Console.Write(", ");
            }
        }
        Console.WriteLine("}");
    }

}